<template>
  <div class="ddns-container">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <h3>DDNS配置</h3>
          <div>
            <el-button type="primary" @click="saveConfig" :loading="loading">保存配置</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-form :model="form" label-position="top" :rules="rules" ref="formRef">
        <!-- Cloudflare API Token -->
        <el-form-item prop="cloudflareAPIToken" required>
          <template #label>
            <div class="form-label-with-help">
              <span>Cloudflare API Token</span>
              <el-tooltip 
                content="在Cloudflare控制面板中生成具有DNS编辑权限的API令牌" 
                placement="right"
              >
                <el-icon class="help-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input 
            v-model="form.cloudflareAPIToken" 
            placeholder="请输入您的Cloudflare API Token"
            show-password
          ></el-input>
        </el-form-item>
        
        <!-- 域名列表 -->
        <el-form-item prop="domainNames" class="domain-list-form-item" required>
          <template #label>
            <div class="form-label-with-help">
              <span>域名列表</span>
              <el-tooltip 
                content="要管理的域名列表，例如：example.com 或 sub.example.com" 
                placement="right"
              >
                <el-icon class="help-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="domain-list-container">
            <div 
              v-for="(domain, index) in form.domainNames" 
              :key="index"
              class="domain-input-group"
            >
              <el-input 
                v-model="form.domainNames[index]" 
                placeholder="example.com"
                class="domain-input"
              >
                <template #append>
                  <el-button 
                    @click="removeDomain(index)" 
                    :disabled="form.domainNames.length <= 1"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
            
            <div class="domain-actions">
              <el-button class="add-button" @click="addDomain">
                <el-icon><Plus /></el-icon> 添加域名
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <!-- 检查间隔 -->
        <el-form-item prop="checkInterval" required>
          <template #label>
            <div class="form-label-with-help">
              <span>检查间隔（秒）</span>
              <el-tooltip 
                content="检查IP地址变化的时间间隔，最小60秒" 
                placement="right"
              >
                <el-icon class="help-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input-number 
            v-model="form.checkInterval" 
            :min="60" 
            :max="86400"
            class="w-100"
          ></el-input-number>
        </el-form-item>
        
        <!-- IP版本 -->
        <el-form-item prop="ipVersion" required>
          <template #label>
            <div class="form-label-with-help">
              <span>IP版本</span>
            </div>
          </template>
          <el-radio-group v-model="form.ipVersion">
            <el-radio label="ipv4">IPv4</el-radio>
            <el-radio label="ipv6">IPv6</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 高级设置 -->
    <el-card class="advanced-card">
      <template #header>
        <div class="card-header">
          <h3>高级设置</h3>
        </div>
      </template>
      
      <el-tabs>
        <!-- IPv4服务 -->
        <el-tab-pane label="IPv4检测服务">
          <p class="tab-description">
            配置用于检测您的公共IPv4地址的服务列表，这些服务应该返回纯文本格式的IP地址
          </p>
          
          <div class="service-list-container">
            <div 
              v-for="(service, index) in form.ipv4Services" 
              :key="'ipv4-' + index"
              class="service-input-group"
            >
              <el-input 
                v-model="form.ipv4Services[index]" 
                placeholder="https://api.ipify.org"
              >
                <template #append>
                  <el-button 
                    @click="removeService('ipv4', index)" 
                    :disabled="form.ipv4Services.length <= 1"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
            
            <div class="service-actions">
              <el-button class="add-button" @click="addService('ipv4')">
                <el-icon><Plus /></el-icon> 添加IPv4检测服务
              </el-button>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- IPv6服务 -->
        <el-tab-pane label="IPv6检测服务">
          <p class="tab-description">
            配置用于检测您的公共IPv6地址的服务列表，这些服务应该返回纯文本格式的IP地址
          </p>
          
          <div class="service-list-container">
            <div 
              v-for="(service, index) in form.ipv6Services" 
              :key="'ipv6-' + index"
              class="service-input-group"
            >
              <el-input 
                v-model="form.ipv6Services[index]" 
                placeholder="https://api6.ipify.org"
              >
                <template #append>
                  <el-button 
                    @click="removeService('ipv6', index)" 
                    :disabled="form.ipv6Services.length <= 1"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
            
            <div class="service-actions">
              <el-button class="add-button" @click="addService('ipv6')">
                <el-icon><Plus /></el-icon> 添加IPv6检测服务
              </el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 日志面板 -->
    <logs-panel class="logs-panel" />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { Delete, Plus, InfoFilled } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import Notification from '../utils/notification'
import LogsPanel from '../components/LogsPanel.vue'

export default {
  name: 'DDNSConfigPage',
  components: {
    Delete,
    Plus,
    InfoFilled,
    LogsPanel
  },
  setup() {
    const formRef = ref(null)
    const loading = ref(false)
    
    // 默认IPv4服务列表
    const defaultIPv4Services = [
      'https://api.ipify.org',
      'https://ifconfig.me/ip',
      'https://icanhazip.com',
      'https://ipinfo.io/ip',
    ]
    
    // 默认IPv6服务列表
    const defaultIPv6Services = [
      'https://api6.ipify.org',
      'https://ifconfig.co/ip',
      'https://ipv6.icanhazip.com',
      'https://v6.ident.me',
      'http://v6.66666.host:66/ip',
    ]
    
    // 表单数据
    const form = reactive({
      cloudflareAPIToken: '',
      domainNames: [''],
      checkInterval: 300,
      ipVersion: 'ipv4',
      ipv4Services: [...defaultIPv4Services],
      ipv6Services: [...defaultIPv6Services]
    })
    
    // 表单验证规则
    const rules = {
      domainNames: [
        { 
          validator: (rule, value, callback) => {
            const nonEmptyDomains = value.filter(d => d.trim() !== '')
            if (nonEmptyDomains.length === 0) {
              callback(new Error('请至少输入一个有效的域名'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ],
      checkInterval: [
        { required: true, message: '请输入检查间隔', trigger: 'blur' },
        { type: 'number', min: 60, message: '检查间隔必须大于等于60秒', trigger: 'blur' }
      ]
    }
    
    // 加载配置数据
    const loadConfig = async () => {
      try {
        const response = await fetch('/api/ddns/config')
        const result = await response.json()
        
        if (result.success && result.data) {
          const data = result.data
          
          form.cloudflareAPIToken = data.cloudflare_api_token || ''
          form.domainNames = [...(data.domain_names || [''])]
          form.checkInterval = data.check_interval || 300
          form.ipVersion = data.ip_version || 'ipv4'
          
          if (data.ipv4_services && data.ipv4_services.length > 0) {
            form.ipv4Services = [...data.ipv4_services]
          }
          
          if (data.ipv6_services && data.ipv6_services.length > 0) {
            form.ipv6Services = [...data.ipv6_services]
          }
        }
      } catch (error) {
        console.error('加载配置失败:', error)
        Notification.error('加载配置失败，请检查后端服务是否正常运行')
      }
    }
    
    // 保存配置
    const saveConfig = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        
        loading.value = true
        
        // 过滤空域名
        const filteredDomains = form.domainNames.filter(d => d.trim() !== '')
        if (filteredDomains.length === 0) {
          filteredDomains.push('')
        }
        
        const configData = {
          cloudflare_api_token: form.cloudflareAPIToken,
          domain_names: filteredDomains,
          check_interval: form.checkInterval,
          ip_version: form.ipVersion,
          ipv4_services: form.ipv4Services,
          ipv6_services: form.ipv6Services
        }
        
        try {
          const response = await fetch('/api/ddns/config', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(configData)
          })
          
          const result = await response.json()
          
          if (result.success) {
            // 显示成功提示消息
            Notification.ddnsSuccess()
          } else {
            // 显示错误提示消息
            Notification.error(result.message || '保存配置失败')
          }
        } catch (error) {
          console.error('保存配置失败:', error)
          // 显示网络错误提示消息
          Notification.networkError()
        }
        
        loading.value = false
      } catch (error) {
        // 表单验证失败
        console.error('表单验证失败:', error)
        // 显示表单验证失败提示
        Notification.formValidationError()
      }
    }
    
    // 重置表单
    const resetForm = () => {
      ElMessageBox.confirm('确定要重置所有配置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 重置为默认初始值
        form.cloudflareAPIToken = ''
        form.domainNames = ['']
        form.checkInterval = 300
        form.ipVersion = 'ipv4'
        form.ipv4Services = [...defaultIPv4Services]
        form.ipv6Services = [...defaultIPv6Services]
        
        if (formRef.value) {
          formRef.value.resetFields()
        }
        
        Notification.success('表单已重置为默认值')
      }).catch(() => {})
    }
    
    // 添加域名输入框
    const addDomain = () => {
      form.domainNames.push('')
    }
    
    // 移除域名输入框
    const removeDomain = (index) => {
      form.domainNames.splice(index, 1)
    }
    
    // 添加服务
    const addService = (type) => {
      if (type === 'ipv4') {
        form.ipv4Services.push('')
      } else {
        form.ipv6Services.push('')
      }
    }
    
    // 移除服务
    const removeService = (type, index) => {
      if (type === 'ipv4') {
        form.ipv4Services.splice(index, 1)
      } else {
        form.ipv6Services.splice(index, 1)
      }
    }
    
    onMounted(() => {
      loadConfig()
    })
    
    return {
      formRef,
      form,
      rules,
      loading,
      saveConfig,
      resetForm,
      addDomain,
      removeDomain,
      addService,
      removeService
    }
  }
}
</script>

<style scoped>
.config-card, 
.advanced-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.domain-list-container {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 16px;
  background-color: #FAFAFA;
  margin-bottom: 8px;
}

.domain-input-group {
  margin-bottom: 10px;
  display: flex;
}

.domain-input-group .el-input {
  flex: 1;
}

.domain-actions {
  display: flex;
  justify-content: flex-start;
}

.service-input-group {
  margin-bottom: 10px;
}

.add-button {
  margin-top: 8px;
}

.w-100 {
  width: 100%;
}

.tab-description {
  margin-bottom: 20px;
  color: var(--text-secondary);
  font-size: 14px;
}

.el-result {
  background: var(--card-bg-color);
  backdrop-filter: var(--blur-effect);
  -webkit-backdrop-filter: var(--blur-effect);
  border-radius: 4px;
  padding: 30px;
  margin-top: 20px;
  border: 1px solid var(--border-color);
}

.service-list-container {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 16px;
  background-color: #FAFAFA;
  margin-bottom: 8px;
}

.service-actions {
  display: flex;
  justify-content: flex-start;
}

.domain-list-form-item {
  margin-bottom: 20px;
}

.form-label-with-help {
  display: flex;
  align-items: center;
}

.form-label-with-help span {
  margin-right: 8px;
}

.help-icon {
  margin-left: 8px;
}

.domain-input {
  flex: 1;
}
</style> 